import { getStorage, setStorage } from '@/utils/storage'
import { tags as courseTags, courseDetail } from '@/mock/courses'

/**
 * 获取课程列表
 */
export function getCourses() {
  const courses = getStorage('courses') ? JSON.parse(getStorage('courses')) : []

  courses.forEach(item => {
    item.tags.forEach((tag, i) => { item.tags[ i ] = courseTags[ tag ] })
  })

  return courses
}

export function getCourse(id) {
  const course = courseDetail[ id ]

  course.bgMap.tags.forEach((item, i) => {
    if (courseTags[ item ]) {
      course.bgMap.tags[ i ] = courseTags[ item ]
    }
  })
  return course
}

/**
 * 设置课程, 想数据追加
 */
export function postCourses(courses = []) {
  let storage = getCourses()

  storage = storage.concat(courses)
  setStorage('courses', JSON.stringify(storage))
  return storage
}

/**
 * 设置改造成功
 * @param {Number} courseId
 * @param {String} url
 */
export function setMyAchievement(data) {
  const myInfo = Vue.prototype.$storeGet('getMyInfo')
  const achievements = JSON.parse(getStorage('courseAchievement'))
  const param = {
    userNumber: myInfo.number,
    courseId: data.courseId,
    url: data.url
  }

  /* 查重 */
  const index = achievements.findIndex(item => item.userNumber === myInfo.number && item.courseId === data.courseId)

  if (index > -1) { // 已经有记录，直接覆盖
    achievements[ index ] = param
  } else {
    achievements.push(param)
  }
  setStorage('courseAchievement', JSON.stringify(achievements))
}

/**
 * 根据课程id获取改造成功
 */
export function getMyAchievement(courseId) {
  const myInfo = Vue.prototype.$storeGet('getMyInfo')
  const achievements = JSON.parse(getStorage('courseAchievement'))

  return achievements.find(item => item.userNumber === myInfo.number && item.courseId === courseId) || null
}
